﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//using DG.Tweening;
using QxFramework.Utilities;

public class GameManager : MonoSingleton<GameManager>, IEventListener
{
    public GameObject GameStartButton;
    public GameObject MoveObj;
    public GameObject temp;
    public GameObject Enemy;
    public GameObject Dice_null;
    //public GameObject MainCamera;
    public GameObject SceneCamera;
    public GameObject Dialogue;
    private int row;

    private List<GameObject> SpawnList = new List<GameObject>();

    GameObject CrystalDice1, CrystalDice2;
    private bool is_Start;
    private Color start = new Color(0.196f, 0.196f, 0.196f, 1.0f);
    private Color end = new Color(0.196f, 0.196f, 0.196f, 0.0f);

    public GameObject HP;
    public GameObject Attack;
    public GameObject Defence;

    private GameObject PickAudio;
    string dialoge = " $ScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition." + "\n"
        + " New-Item -Type Directory -Path (Join-Path $saveTo '/ tmp /') -ErrorAction SilentlyContinue >$null"
        + "\n" + " write-verbose Replacing /etc/profile.d/git-prompt.sh with our git-prompt.sh"
        + "\n" + " Copy-Item $($SaveTo + 'git-prompt.sh) $($SaveTo + 'git-for-windows/etc/profile.d/git-prompt.sh')"
        + "\n" + " Add-AppveyorMessage -Message Building Cmder v$version was successful. -Category Information"
        + "\n" + " msbuild CmderLauncher.vcxproj /t:Clean,Build /p:configuration=Release"
        + "\n" + " Extract-Archive $tempArchive $s.name"
        + "\n" + " Download-File -Url $s.url -File $vend$tempArchive -ErrorAction Stop"
        + "\n" + " Delete-Existing $tempArchive"
        + "\n" + " Write-Verbose Getting $($s.name) from URL $($s.url)"
        + "\n" + " New-Item -Type Directory -Path (Join-Path $saveTo ) -ErrorAction SilentlyContinue >$null"
        + "\n" + " write-verbose $('Stopping' + $ssh_agent.path + !)"
        + "\n" + " Extract-Archive $tempArchive $s.name"
        + "\n" + " # Config folder location"
        + "\n" + " $sourcesPath = .vendorsources.json"
        + "\n" + " [CmdletBinding(SupportsShouldProcess=$true)]"
        + "\n" + " Build cmder with your own packages. See vendor/sources.json for the syntax you need to copy."
        + "\n" + " Loading Success"
        + "\n" + "Press any key to Play";

    public int Process;

    public int Row
    {
        get
        {
            if (Process < 10)
            {
                row = Random.Range(1, 11);
            }
            else if(Process>9 && Process < 14)
            {
                row = Random.Range(4, 15);
            }
            else
            {
                row = Random.Range(10, 20);
            }
            return row;
        }
    }

    private void Awake()
    {
        PickAudio=GameObject.Find("AudioPlayer/PickAudio");
        is_Start = true;
        EventNodeCore.GetInstance().AttachEventListener(EventDef.PickCrystal, this);
        //加载CSV表格
        Data.Instance.LoadTable();
        Destroy(temp); // TODO 删掉！
        //GameStartButton.SetActive(true); // TODO 删掉！
        MoveObj = Resources.Load("MoveObj") as GameObject;
        Dice_null = Resources.Load("Dice_null") as GameObject;
        //MainCamera = GameObject.Find("Main_Camera");
        SceneCamera = Resources.Load("SceneCamera_") as GameObject;
        StartCoroutine(GameStartDialogue(Dialogue));
    }
    private void OnDisable()
    {
        EventNodeCore.GetInstance().DetachEventListener(EventDef.PickCrystal, this);
    }
    public void GameStart()
    {
        Dialogue.GetComponent<Text>().text = "";
        //要移开，不然会挡住
        Dialogue.transform.position = new Vector3(10000, 0, 0);
        //MapManager.Instance.SpawnMap(new List<Vector3> { Vector3.zero/*,Vector3.right*3,Vector3.forward*3,Vector3.right*3+Vector3.forward*3 */});
        GameStartButton.SetActive(false);
        //GameObject moveobj = Instantiate(MoveObj, Vector3.up * 1.5f, Quaternion.identity, MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.up].Dices[Vector3.up].Obj.transform.GetChild(0));
        //MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.up].Dices[Vector3.up].Controller.FlushChild(moveobj.transform.Find("Player").gameObject);
        ////GameObject enemy = Instantiate(Enemy, MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.left].Dices[Vector3.left].obj.transform.GetChild(0));
        ////MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.left].Dices[Vector3.left].Controller.FlushChild(enemy);
        GameObject crysal = Instantiate(Resources.Load("Prop/Crystal_White") as GameObject, new Vector3(0, -1.5f, 0), Quaternion.identity);
        crysal.transform.localScale = new Vector3(3, 3, 3);
        crysal.transform.position = new Vector3(1, 0.5f, 0);
        RoundManager.Instance.GameRoundStart();
    }
    public int EventPriority()
    {
        return 0;
    }

    public bool HandleEvent(int id, object param1, object param2)
    {
        if (id == EventDef.PickCrystal)
        {
            Debug.Log("拾取晶体");
            if (Process < 6)
            {
                string Description = TableAgent.Instance.GetString("ProgressDiscription", Process.ToString(), "Description");
                EventNodeCore.GetInstance().SendMessage(-EventDef.PickCrystal, Description, null);
                PickAudio.GetComponent<AudioSource>().Play();
            }
            else
            {
                ProcessFuc();
            }
            //ProcessFuc();
        }
        return false;
    }

    public void ProcessFuc()
    {
        switch (Process)
        {
            case 0: //认识你自己
                //string Description = TableAgent.Instance.GetString("ProgressDiscription", Process.ToString(), "Description");
                //EventNodeCore.GetInstance().SendMessage(-EventDef.PickCrystal, Description, null);

                Camera.main.cullingMask |= (1 << 8);  // 打开层
                Debug.LogWarning("first");
                CrystalDice1 = Instantiate(Dice_null, new Vector3(1, 1, 0), Quaternion.identity);
                CrystalDice2 = Instantiate(Dice_null, new Vector3(0, 1, 0), Quaternion.identity);

                MapManager.Instance.SpawnObj(CrystalDice2.GetComponent<DiceController>().Data, Resources.Load("Prop/Crystal_White") as GameObject);
                MapManager.Instance.SpawnObj(CrystalDice1.GetComponent<DiceController>().Data, Resources.Load("MoveObj") as GameObject);

                //GameObject moveobj = Instantiate(MoveObj, new Vector3(1,1.5f,0), Quaternion.identity, CrystalDice1.transform.GetChild(0));

                //Destroy(MainCamera);
                break;
            case 1: // 天圆地方
                    //Description = TableAgent.Instance.GetString("ProgressDiscription", Process.ToString(), "Description");
                    //EventNodeCore.GetInstance().SendMessage(-EventDef.PickCrystal, Description, null);

                // 生成地图               
                Destroy(CrystalDice1);
                Destroy(CrystalDice2);
                MapManager.Instance.SpawnMap(new List<Vector3> { Vector3.zero });

                // 正式注册角色
                PlayerManager.Instance.gameObject.transform.parent.parent = MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.up].Dices[Vector3.up].Obj.transform.GetChild(0);
                MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.up].Dices[Vector3.up].Controller.FlushChild(PlayerManager.Instance.gameObject);
                PlayerManager.Instance.Data.FlushCoordinate(MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.up].Dices[Vector3.up]);

                // 摄像机
                Camera.main.cullingMask = ~(1 << 6);  // 打开层
                Camera.main.clearFlags = CameraClearFlags.Depth;
                Instantiate(Resources.Load("SceneCamera_") as GameObject, Vector3.zero, Quaternion.identity);

                // 生成四个晶体
                MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.forward].Controller.SpawnObj(0.ToString());
                MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.back].Controller.SpawnObj(0.ToString());
                MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.left].Controller.SpawnObj(0.ToString());
                MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.right].Controller.SpawnObj(0.ToString());
                break;
            case 2: // 生成血属性
                    //    Description = TableAgent.Instance.GetString("ProgressDiscription", Process.ToString(), "Description");
                    //    EventNodeCore.GetInstance().SendMessage(-EventDef.PickCrystal, Description, null);


                int j = 0;
                foreach (var dice in PlayerManager.Instance.Data.CoorDinate.Surface.Dices)
                {
                    if (j == 1)
                    {
                        SpawnList.Add(dice.Value.Controller.SpawnObj("Prop/sushi"));
                        break;
                    }
                    j++;
                    //生成属性UI
                    GameObject Hp = GameObject.Find("UI/Player/PlayerHP");
                    Hp.SetActive(true);
                    Vector3 StartValue1 = Hp.transform.position;
                    Vector3 endValue1 = new Vector3(StartValue1.x - 600f, StartValue1.y + 380f, StartValue1.z);
                    //Hp.transform.DOMove(endValue1, 1.0f, false);
                }
                break;
            case 3: // 生成攻击属性
                //Description = TableAgent.Instance.GetString("ProgressDiscription", Process.ToString(), "Description");
                //EventNodeCore.GetInstance().SendMessage(-EventDef.PickCrystal, Description, null);

                int k = 0;
                foreach (var dice in PlayerManager.Instance.Data.CoorDinate.Surface.Dices)
                {
                    if (k == 1)
                    {
                        SpawnList.Add(dice.Value.Controller.SpawnObj("Prop/Knife"));
                        break;
                    }
                    k++;
                }
                //生成属性UI
                GameObject ATk = GameObject.Find("UI/Player/PlayerAttack");
                ATk.SetActive(true);
                Vector3 StartValue = ATk.transform.position;
                Vector3 endValue = new Vector3(StartValue.x - 600f, StartValue.y + 280f, StartValue.z);
                //ATk.transform.DOMove(endValue, 1.0f, false);
                break;
            case 4: // 生成防御属性
                //Description = TableAgent.Instance.GetString("ProgressDiscription", Process.ToString(), "Description");
                //EventNodeCore.GetInstance().SendMessage(-EventDef.PickCrystal, Description, null);

                int l = 0;
                foreach (var dice in PlayerManager.Instance.Data.CoorDinate.Surface.Dices)
                {
                    if (l == 1)
                    {
                        SpawnList.Add(dice.Value.Controller.SpawnObj("Prop/Sheld"));
                        break;
                    }
                    l++;
                }
                //生成属性UI
                GameObject Def = GameObject.Find("UI/Player/PlayerDefence");
                Def.SetActive(true);
                Vector3 StartValue3 = Def.transform.position;
                Vector3 endValue3 = new Vector3(StartValue3.x - 600f, StartValue3.y + 180f, StartValue3.z);
                //Def.transform.DOMove(endValue3, 1.0f, false);
                break;
            case 5: // 生成Enemy概念，并开始CheckSpawn协程
                //Description = TableAgent.Instance.GetString("ProgressDiscription", Process.ToString(), "Description");
                //EventNodeCore.GetInstance().SendMessage(-EventDef.PickCrystal, Description, null);
                int i = 0;
                foreach (var dice in PlayerManager.Instance.Data.CoorDinate.Surface.Dices)
                {
                    if (i == 1)
                    {
                        SpawnList.Add(dice.Value.Controller.SpawnObj("Enemy/Chicken"));
                        StartCoroutine(CheckSpawn());
                        break;
                    }
                    i++;
                }
                //PlayerManager.Instance.Data.CoorDinate.Surface.Dices[PlayerManager.Instance.Data.CoorDinate.DiceCoordinate + PlayerManager.Instance.Data.Towards].Controller.SpawnObj("Enemy/Snake");
                break;
            default:
                MapManager.Instance.PickUpCrystal();
                break;

        }
        Process++;
    }
    /// <summary>
    /// 如果生成的四个物体都消耗掉了，生成一个晶体，游戏进入流程循环 
    /// </summary>
    /// <returns></returns>
    private IEnumerator CheckSpawn()
    {
        Debug.Log(SpawnList[0].gameObject);
        Debug.Log(SpawnList[1].gameObject);
        Debug.Log(SpawnList[2].gameObject);
        Debug.Log(SpawnList[3].gameObject);
        while (SpawnList[0].gameObject != null || SpawnList[1].gameObject != null || SpawnList[2].gameObject != null || SpawnList[3].gameObject != null)
        {
            yield return null;
        }
        MapData.Instance.Cubes[Vector3.zero].Surfaces[Vector3.down].Controller.SpawnObj(0.ToString());
        MapManager.Instance.Time2CheckIt = true;
    }

    /// <summary>
    /// 开场动画
    /// </summary>
    /// <param name="Text"></param>
    /// <returns></returns>
    IEnumerator GameStartDialogue(GameObject Text)
    {
        //for (int index = 1; index < 4; index++)
        //{
        string s = "";
        int index = 1;
        int i = 0;
        string dialogue = TableAgent.Instance.GetString("GameDialoge", index.ToString(), "Dialoge");
        Debug.Log(dialogue);
        //while (i < dialoge.Length)
        //{
        //    s += dialoge[i].ToString();
        //    Text.GetComponent<Text>().text = s;
        yield return new WaitForSeconds(0.005f);
        //    i++;
        //}
        is_Start = false;
        //Text.GetComponent<Text>().text = dialogue.ToString();
        //死循环用不了
        //while (Text.GetComponent<Text>().color.a > 0.5f)
        //{
        //    float lerp = Mathf.PingPong(Time.time, 1.0f);
        //    Text.GetComponent<Text>().color = Color.Lerp(start, end, lerp);
        //    Debug.Log(Text.GetComponent<Text>().color.a);
        //}
        //}
        //这个Text会挡住Button，要移开
        //Text.transform.position = new Vector3(1000, 0, 0);
        //GameStartButton.SetActive(true); // TODO 删掉/*！*/
        //GameStartButton.GetComponent<Button>().onClick.AddListener(GameStart);
    }
    private void Update()
    {
        if (!is_Start)
        {
            if (Input.anyKeyDown)
            {
                GameStart();
                is_Start = true;
            }

        }
    }

}
